﻿using GenericHtml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using WLFramework.Data.Linq;
using WLFramework.Json;
using WLFramework.Mapping;
using WLFramework.Web;

namespace SampleSite.admin.ajax
{
    /// <summary>
    /// setRoleMenus 的摘要说明
    /// </summary>
    public class setRoleMenus : AjaxHttpHandler
    {
        public class JsonData
        {
            public int r_id { get; set; }
            public int a_id { get; set; }
            public int[] menus { get; set; }
        }

        public override void OnProcessRequest(HttpContext context)
        {
            var input = context.GetValueByName<string>("data");
            if (IsNullOrWhiteSpace(input))
                throw new Exception("参数错误");

            JsonData d = new JsonData();
            var data = JSON.Instance.ToObject<JsonData>(input);

            using (CommandHelper db = new CommandHelper(CommandMethod.Write))
            {
                var ar = (from p in db.Context.sys_RoleApplication
                          where p.A_ID == data.a_id &&
                                p.R_ID == data.r_id &&
                                p.A_State == 1
                          select new Tuple<sys_Applications, sys_Roles>(
                              p.sysRoleApplicationsysApplications,
                              p.sysRoleApplicationsysRoles)).First();
                var app = ar.Item1;
                var role = ar.Item2;

                db.Context.BeginTransaction();

                db.Context.sys_RoleModule.Where(k =>
                    k.R_ID == role.R_ID &&
                    k.sysRoleModulesysModuleList.M_AppID == app.A_ID)
                  .Delete();

                List<sys_RoleModule> list = new List<sys_RoleModule>();
                foreach (var m_id in data.menus ?? new int[0])
                {
                    list.Add(new sys_RoleModule()
                    {
                        R_ID = role.R_ID,
                        M_ID = m_id,
                        M_State = 1,
                        M_Value = 0x02
                                | 0x04
                                | 0x08
                                | 0x10
                    });
                }

                db.Context.InsertBatch<sys_RoleModule>(list);

                db.Context.CommitTransaction();
            }

            context.Response.Write(JSON.Instance.ToJSON(JSONResult.Success));
        }
    }
}